package com.kmfish.smsbackup;

import java.util.Date;
import java.util.TreeSet;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class SmsBackup extends Activity implements OnItemClickListener, OnClickListener {
	
	public static final String ACTION_NEW_NOTE             = "com.evernote.action.CREATE_NEW_NOTE";

	private ListView mListView;
	private EditText mNoteTitle;
	private Button mSendBtn;
	private SmsItemAdapter mSmsAdapter;
	private boolean isInTopView;
	private int smsBoxType = 0;
	private ProgressDialog mProgressDialog;
	
	private static final int SMS_INBOX = 0;
	private static final int SMS_SENT_BOX = 1;
	private static final int SMS_THREAD = 2;
	private static final String SMSBACKUP = "smsbackup"; 
	 
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mListView = (ListView) findViewById(R.id.listView);
        mNoteTitle = (EditText) findViewById(R.id.note_title);
        mSendBtn = (Button) findViewById(R.id.send);
        mSmsAdapter = new SmsItemAdapter(this);
        updateTopListView();
    }
    
	/**
	 * update the top page for listView.
	 */
	private void updateTopListView()
	{
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				R.layout.list_top_item);
		adapter.add(getResources().getString(R.string.inbox));
		adapter.add(getResources().getString(R.string.sentbox));
		adapter.add(getResources().getString(R.string.thread));
		mListView.setAdapter(adapter);
		mListView.setOnItemClickListener(this);

		mNoteTitle.setVisibility(View.GONE);
		mSendBtn.setVisibility(View.GONE);
		isInTopView = true;
	}

	@Override
	public void onBackPressed() {
		if (!isInTopView) 
		{
			updateTopListView();
			return;
		}
		super.onBackPressed();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (isInTopView) {
			int smsBoxType = SMS_INBOX;
			if (0 == position) { // inbox
				smsBoxType = SMS_INBOX;
			}else if (1 == position) { // sentbox
				smsBoxType = SMS_SENT_BOX;
			}else if (2 == position) { // sentbox
				smsBoxType = SMS_THREAD;
			}
			
			mProgressDialog = ProgressDialog.show(SmsBackup.this, "Wait", "loading......");
			new LoadListTask().execute();
			this.smsBoxType = smsBoxType;
		} else {

		}		
	}
	
	private class LoadListTask extends AsyncTask<Void, Void, Integer> 
	{
		MySmsMessage[] messages = null;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mNoteTitle.setVisibility(View.VISIBLE);
			Date date = new Date();
			mNoteTitle.setText(Util.DatetoString(date, "yyyyMMddHHmmss") + SMSBACKUP);
			mSendBtn.setVisibility(View.VISIBLE);
			mSendBtn.setOnClickListener(SmsBackup.this); 
			
		}
		
		@Override
		protected Integer doInBackground(Void... params) {
			if (smsBoxType == SMS_THREAD) {
				messages = SmsUtil.getSmsMessagesByThread(SmsBackup.this);
				mSmsAdapter.mode = SmsItemAdapter.THREAD_MODE; 
			}else {
				switch (smsBoxType) {
				case SMS_INBOX:
					messages = SmsUtil.getSmsMessages(SmsBackup.this, true);
					break;
				case SMS_SENT_BOX:
					messages = SmsUtil.getSmsMessages(SmsBackup.this, false);
					break;
				default:
					break;
				}
				mSmsAdapter.mode = SmsItemAdapter.NORMAL_MODE;
			}

			return null;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			isInTopView = false;
			mSmsAdapter.clear();
			for (MySmsMessage sms : messages) {
				mSmsAdapter.add(sms);
			}
			mListView.setAdapter(mSmsAdapter);
			mListView.setOnItemClickListener(SmsBackup.this);
			updateHandler.sendEmptyMessage(0);
		}
	}
	
	private Handler updateHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// 关闭ProgressDialog
			mProgressDialog.dismiss();
		}
	};

	@Override
	public void onClick(View v) {
		mProgressDialog = ProgressDialog.show(this, "Waiting", "loading sms......");
		new LoadNoteTask().execute();
	}

	private String createNote() {
		StringBuilder backupNote = new StringBuilder();
		// sort by checkedItems key
		TreeSet<Integer> keys = new TreeSet<Integer>(mSmsAdapter.checkedItems.keySet());
		if (smsBoxType != SMS_THREAD) {
			for (Integer checkedPos : keys) {
				if (mSmsAdapter.checkedItems.get(checkedPos)) {
					MySmsMessage sms = mSmsAdapter.getItem(checkedPos);
					backupNote.append(createNoteContent(sms, checkedPos));
					backupNote.append("\n");
				}
			}
		} else {
			for (Integer checkedPos : keys) {
				if (mSmsAdapter.checkedItems.get(checkedPos)) {
					MySmsMessage[] smsMessages = mSmsAdapter.getSmsMessages(checkedPos);
					backupNote.append("------start------\n");
					for (MySmsMessage sms : smsMessages) {
						backupNote.append(createNoteContent(sms, checkedPos));
					}
					backupNote.append("------end------\n\n");
				}
			}
		}
		
		return backupNote.toString();
	}
	
	public String getContactStr(MySmsMessage sms, int position) {
		return SmsItemAdapter.createTypeStr(sms.type, mSmsAdapter.createContactStr(sms.address, 0, false));
	}
	
	private String createNoteContent(MySmsMessage sms, int position)
	{
		StringBuilder backupNote = new StringBuilder();
		String dateText = Util.DatetoString(new Date(sms.timestamp), "yyyy-MM-dd HH:mm:ss");
		backupNote.append(dateText);
		backupNote.append("\n");
		backupNote.append(getContactStr(sms, position));
		backupNote.append("\n");
		backupNote.append(sms.body);
		backupNote.append("\n");
		return backupNote.toString();
	}
	
	private void sendNote2Evernote(String title, String body) {
		if (null == body || body.length() <= 0) {
			 Toast.makeText(this, R.string.err_no_item_selected, Toast.LENGTH_SHORT).show();
			return;
		}
		
		Log.d("onSent", title + "\n" + body);
	    Intent intent = new Intent();
	    intent.setAction(ACTION_NEW_NOTE);

	    // Set the note's title and plaintext content
	    intent.putExtra(Intent.EXTRA_TITLE, title);
	    intent.putExtra(Intent.EXTRA_TEXT, body);

	    try {
	      startActivity(intent);
	    } catch (android.content.ActivityNotFoundException ex) {
	      Toast.makeText(this, R.string.err_activity_not_found, Toast.LENGTH_SHORT).show();
	    } 
	}
	
	private class LoadNoteTask extends AsyncTask<Void, Void, Integer> 
	{
		String note = "";
		@Override
		protected Integer doInBackground(Void... params) {
			note = createNote();
			return null;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			sendNote2Evernote(mNoteTitle.getText().toString(), note);
			updateHandler.sendEmptyMessage(0);
		}
	}
}